<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%"
        size="small"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          type="index"
          align="center"
          label="序号"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getRechargeList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="50%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
        size="small"
      >
        <el-form-item label="充值金额" prop="money">
          <el-input v-model="form.money" placeholder="充值金额" clearable>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="赠送金额" prop="gift_amount">
          <el-input v-model="form.gift_amount" placeholder="赠送金额" clearable>
            <template slot="append">元</template>
          </el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false" size="mini"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSave(false)" size="mini"
          >保存</el-button
        >
        <el-button type="primary" size="mini" @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getRecharges,
  addRecharge,
  updateRecharge,
  delRecharge,
  delRecharges,
} from "@/api/wechat";

import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  money: 0,
  gift_amount: 0,
};

export default {
  name: "RechargeList",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    const checkGiftMoney = (rule, value, callback) => {
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value < 0) {
          callback(new Error("必须大于等于零"));
        } else {
          callback();
        }
      }
    };
    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        money: [{ validator: checkMoney, trigger: "blur" }],
        // gift_amount: [{ validator: checkGiftMoney, trigger: "blur" }],
      },

      tableColumns: [
        {
          key: "money",
          title: "充值金额(元)",
          align: "center",
        },
        // {
        //   key: "gift_amount",
        //   title: "赠送金额(元)",
        //   align: "center",
        // },
        {
          key: "update_date",
          title: "创建时间",
          align: "center",
        },
      ],

      title: "充值金额",
      dialogVisible: false,
      dialogType: "new",
      datas: [],
      selections: [],

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getRechargeList();
  },
  methods: {
    getRechargeList() {
      this.listLoading = true;
      getRecharges()
        .then((res) => {
          this.datas = res;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取数据失败!");
          this.listLoading = false;
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
      console.log(this.selections);
    },
    handleBatchDelete() {
      if (this.selections.length === 0) {
        this.$message.warning("请选择要删除的记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delRecharges(sel_ids);
          this.getRechargeList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getRechargeList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = scope.row;
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除这条记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delRecharge(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          res = await updateRecharge(this.form);
        } else {
          res = await addRecharge(this.form);
        }
        this.getRechargeList();
        const { money } = res;
        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>充值金额: ${money}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.dialog .el-form {
  margin-top: 20px;
}
.el-form-item {
  margin-bottom: 15px;
}
</style>